// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: juntang

#include "coin2/exchange/bitget/api_order/native_rest_async_asio_subscriber.h"

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>

#include "coin2/base/log.h"

namespace coin2::exchange::bitget::api_order {

void BitgetRestAsyncAsioSubscriber::QueryBalance() {
  RestParams params;
  auto http_context = rest_client()->QueryAccount(params);
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&BitgetRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BitgetRestAsyncAsioSubscriber::QueryOpenOrders(const std::string& native_symbol) {
  RestParams params;
  params.set_symbol(native_symbol);
  auto http_context = rest_client()->QueryOpenOrders(params);
  if (!http_context) return;
  http_context->handler =
      std::bind(&BitgetRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BitgetRestAsyncAsioSubscriber::QueryHistoryOrders(const std::string& native_symbol) {
  RestParams params;
  params.set_symbol(native_symbol);
  auto http_context = rest_client()->QueryAllOrders(params);
  if (!http_context) return;
  http_context->handler =
      std::bind(&BitgetRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BitgetRestAsyncAsioSubscriber::QueryFills(const std::string& native_symbol) {
  RestParams params;
  params.set_symbol(native_symbol);
  auto http_context = rest_client()->QueryFills(params);
  if (!http_context) return;
  http_context->handler =
      std::bind(&BitgetRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BitgetRestAsyncAsioSubscriber::SubscribeAsync() {
  AddPeriodicTask(
      std::bind(&BitgetRestAsyncAsioSubscriber::QueryBalance, this),
      config_.query_account_balance_period_sec(),
      "query_balance");

  AddPeriodicTask(
      std::bind(&BitgetRestAsyncAsioSubscriber::QueryOpenOrders, this, ""),
      config_.query_open_orders_period_sec(),
      "query_open_orders");

  const auto symbol_list = native_symbols();

  AddPeriodicTask(
      std::bind(&BitgetRestAsyncAsioSubscriber::QueryHistoryOrders, this, std::placeholders::_1),
      config_.query_cancel_orders_period_sec(),
      "query_history_orders",
      symbol_list);

  AddPeriodicTask(
      std::bind(&BitgetRestAsyncAsioSubscriber::QueryFills, this, std::placeholders::_1),
      config_.query_fill_period_sec(),
      "query_fills",
      symbol_list);
}
}  // namespace coin2::exchange::bitget::api_order
